'use strict';

const Service = require('egg').Service;

class CacheSvc extends Service {
  async get(key) {
    const {redis, logger} = this.app;
    const t = Date.now();
    let data = await redis.get(key);
    if (!data) return;
    try {
      data = JSON.parse(data);
    } catch (e) {
      logger.error(e);
      data = [];
    }
    const duration = (Date.now() - t);
    logger.info(key, duration);
    return data;
  }

  async setex(key, value, seconds) {
    const {redis, logger} = this.app;
    const t = Date.now();
    value = JSON.stringify(value);
    if (seconds) {
      await redis.set(key, value, 'EX', seconds);
    } else {
      await redis.set(key, value);
    }
    const duration = (Date.now() - t);
  }

  async incr(key, seconds) {
    const {redis, logger} = this.app;
    const t = Date.now();
    const result = await redis.multi().incr(key).expire(key, seconds)
      .exec();
    const duration = (Date.now() - t);
    return result[0][1];
  }

  async del(key) {
    const {redis, logger} = this.app;
    await redis.del(key);
  }


  async sadd(key, value, seconds) {
    if (value.length == 0) return;
    const {redis, logger} = this.app;
    if (seconds) {
      await redis.multi().sadd(key, value).expire(key, seconds).exec();
    } else {
      await redis.sadd(key, value);
    }
  }


  async smembers(key) {
    const {redis, logger} = this.app;
    let result = await redis.smembers(key);
    return result;
  }


  async lpush(key, values) {
    if (values.length == 0) return;
    const {redis, logger} = this.app;
    if (Array.isArray(values)) {
      values.reverse();
      for (let item of values) {
        await redis.lrem(key, 0, item);
      }
    }
    let result = await redis.lpush(key, values);
    return result;
  }

  async lrange(key) {
    const {redis, logger} = this.app;
    let result = await redis.lrange(key, 0, -1);
    return result;
  }


  async exists(key) {
    const {redis, logger} = this.app;
    let result = await redis.exists(key);
    return result;
  }


  async publish(message) {
    await this.app.redis.publish('ts1', message);
  }
}

module.exports = CacheSvc;
